package com.ghck.server.controller;

import java.security.Principal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.ghck.server.controller.access.ArgIndexForPrintLog;
import com.ghck.server.exception.GhckException;
import com.ghck.server.exception.ErrorConstant;
import com.ghck.server.model.Appointment;
import com.ghck.server.model.HospitalDict;
import com.ghck.server.model.query.AppointmentQuery;
import com.ghck.server.model.query.DoctorQuery;
import com.ghck.server.model.response.DoctorAppointmentRes;
import com.ghck.server.model.response.DoctorRes;
import com.ghck.server.model.response.ResultList;
import com.ghck.server.model.response.ResultObject;
import com.ghck.server.security.AjkUserDetails;
import com.ghck.server.service.AppointmentService;
import com.ghck.server.service.DoctorService;
import com.ghck.server.service.HospitalDictService;
import com.ghck.server.service.RegionDictService;
import com.ghck.server.utils.AjkUtil;
import com.ghck.server.utils.IntegerUtil;

/**
 * 专家团队
 * @author kk
 *
 */
@RequestMapping("/doctor")
@RestController
public class DoctorController {
	
	Logger logger = LoggerFactory.getLogger(DoctorController.class);

	@Autowired
	RegionDictService regionDictService;

	@Autowired
	DoctorService doctorService;

	@Autowired
	HospitalDictService hospitalDictService;
	
	@Autowired
	AppointmentService appointmentService;


	//查询专家团队
	/**
	 *专家团队列表
	 */
	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public ResultList<DoctorRes> findMyEasemodAccount(Integer regionId,Integer departmentId,Integer startId,Integer endId,Integer start,Integer limit,Principal principal){
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		if(null == user){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		Integer userId = Integer.parseInt(principal.getName());
		DoctorQuery query = new DoctorQuery();
		query.setStartId(startId);
		query.setStart(start);
		query.setEndId(endId);
		query.setLimit(limit);
		query.setUserId(userId);
		query.setDepartmentId(departmentId);
		if(IntegerUtil.isPositiveInteger(regionId)){
			List<Integer> regionids = regionDictService.findSelfAllChildrenId(regionId);
			if (CollectionUtils.isNotEmpty(regionids)) {
				List<HospitalDict> hospitalDicts = hospitalDictService.findByRegionIdsInCache(regionids);
				List<Integer> hids = new ArrayList<Integer>();
				if (CollectionUtils.isNotEmpty(hospitalDicts)) {
					for (HospitalDict hospitalDict : hospitalDicts) {
						hids.add(hospitalDict.getId());
					}
					query.setHospitalIds(hids);
				}
				else{
					hids.add(-1);
					query.setHospitalIds(hids);
				}
			}
		}
		List<DoctorRes> doctorRes =  doctorService.findDoctorByQuery(query);
		return new ResultList<>(doctorRes);
	}

	/**
	 *专家详情
	 */
	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/details/{doctorId}", method = RequestMethod.GET)
	public ResultObject<DoctorRes> findDetailById(@PathVariable("doctorId") Integer doctorId,Principal principal){
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		if(null == user){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		Integer userId = Integer.parseInt(principal.getName());
		DoctorRes res = null;
		if(IntegerUtil.isPositiveInteger(doctorId)){
			res = doctorService.findDoctorById(doctorId);
		}
		return new ResultObject<>(res);
	}

	/**
	 *专家预约
	 *需要检查用户的用户名称是否填写
	 */
	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/appointment/{doctorId}/{appointmentTimeTs}", method = RequestMethod.POST)
	public ResultObject<Integer> appointment(@PathVariable("doctorId") Integer doctorId,@PathVariable("appointmentTimeTs") long appointmentTimeTs,Principal principal){
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		if(null == user){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		Integer userId = Integer.parseInt(principal.getName());
		Appointment domain = new Appointment();
		Date appointmentTime = new Date(appointmentTimeTs);
		domain.setAppointmentTime(appointmentTime);
		if(appointmentTime==null || appointmentTime.getTime()<System.currentTimeMillis()){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"请指定预约时间，且预约时间不能是过去时间");
			logger.info("专家预约失败",exception);
			throw exception;
		}
		if(!IntegerUtil.isPositiveInteger(userId)){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"请登录！");
			logger.info("专家预约失败",exception);
			throw exception;
		}
		if(!IntegerUtil.isPositiveInteger(doctorId)){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"请指定预约的专家");
			logger.info("专家预约失败",exception);
			throw exception;
		}
		
		domain.setDoctorId(doctorId);
		domain.setUserId(userId);
		Integer id = appointmentService.insertAppointment(domain);
		
		return new ResultObject<>(id);
	}

	/**
	 *我的预约列表
	 */
	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/appointment/list", method = RequestMethod.GET)
	public ResultList<DoctorAppointmentRes> findMyEasemodAccount(Long startTimeTs ,Long endTimeTs,Integer startId,Integer endId,Integer start,Integer limit,Principal principal){
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		if(null == user){
			throw new GhckException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		Integer userId = Integer.parseInt(principal.getName());
		AppointmentQuery query = new AppointmentQuery();
		query.setStartId(startId);
		query.setStart(start);
		query.setEndId(endId);
		query.setLimit(limit);
		query.setUserId(userId);
		if(startTimeTs!=null && startTimeTs>0L){
			query.setStartTime(new Date(startTimeTs));
		}
		if(endTimeTs!=null && endTimeTs>0L){
			query.setEndTime(new Date(endTimeTs));
		}
		List<DoctorAppointmentRes> res = appointmentService.findAppointmentByQuery(query);
		
		return new ResultList<>(res);
	}

}
